package top.iszsq.config.format;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author zsq
 * @date 2021/6/9 11:19
 **/
public class DatetimeDeserializer extends JsonDeserializer<LocalDateTime> {

    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public LocalDateTime deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        String dateStr = node.asText();

        LocalDateTime parse = null;
        if (dateStr != null && !"".equals(dateStr.trim())) {
            try {
                parse = LocalDateTime.parse(dateStr);
            } catch (Exception e) {
                parse = LocalDateTime.parse(dateStr, dateFormatter);
            }
        }

        return parse;
    }
}
